package com.lxblyw.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lxblyw.entity.Employee;
import com.lxblyw.service.EmployeeService;
import com.lxblyw.util.Const;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String captcha = request.getParameter("captcha");
		
		if(SimpleImageCaptchaServlet.validateResponse(request, captcha)) {
		
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			
			HttpSession session = request.getSession();
			
			Employee employee = null;
			
			try {
				employee = new EmployeeService().login(username, password);
			} catch (Exception e) {
				String msg = e.getMessage();
				session.setAttribute("msg", msg);
				response.sendRedirect("index.jspx");
				return;
			}
			
			if(employee != null) {
				session.setAttribute(Const.EMPLOYEE_IN_SESSION,employee);
				response.sendRedirect("project.jspx");
			} else {
				response.sendRedirect("index.jspx?code=1001");
			}
		
		} else {
			response.sendRedirect("index.jspx?code=10003");
		}
	}

}
